home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / distutils / util.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  16KB  |  463 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """distutils.util
  5.  
  6. Miscellaneous utility functions -- anything that doesn't fit into
  7. one of the other *util.py modules.
  8. """
  9. __revision__ = '$Id: util.py 74807 2009-09-15 19:14:37Z ronald.oussoren $'
  10. import sys
  11. import os
  12. import string
  13. import re
  14. from distutils.errors import DistutilsPlatformError
  15. from distutils.dep_util import newer
  16. from distutils.spawn import spawn
  17. from distutils import log
  18.  
  19. def get_platform():
  20.     """Return a string that identifies the current platform.  This is used
  21.     mainly to distinguish platform-specific build directories and
  22.     platform-specific built distributions.  Typically includes the OS name
  23.     and version and the architecture (as supplied by 'os.uname()'),
  24.     although the exact information included depends on the OS; eg. for IRIX
  25.     the architecture isn't particularly important (IRIX only runs on SGI
  26.     hardware), but for Linux the kernel version isn't particularly
  27.     important.
  28.  
  29.     Examples of returned values:
  30.        linux-i586
  31.        linux-alpha (?)
  32.        solaris-2.6-sun4u
  33.        irix-5.3
  34.        irix64-6.2
  35.  
  36.     Windows will return one of:
  37.        win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
  38.        win-ia64 (64bit Windows on Itanium)
  39.        win32 (all others - specifically, sys.platform is returned)
  40.  
  41.     For other non-POSIX platforms, currently just returns 'sys.platform'.
  42.     """
  43.     if os.name == 'nt':
  44.         prefix = ' bit ('
  45.         i = string.find(sys.version, prefix)
  46.         if i == -1:
  47.             return sys.platform
  48.         j = string.find(sys.version, ')', i)
  49.         look = sys.version[i + len(prefix):j].lower()
  50.         if look == 'amd64':
  51.             return 'win-amd64'
  52.         if look == 'itanium':
  53.             return 'win-ia64'
  54.         return sys.platform
  55.     if os.name != 'posix' or not hasattr(os, 'uname'):
  56.         return sys.platform
  57.     (osname, host, release, version, machine) = os.uname()
  58.     osname = string.lower(osname)
  59.     osname = string.replace(osname, '/', '')
  60.     machine = string.replace(machine, ' ', '_')
  61.     machine = string.replace(machine, '/', '-')
  62.     if osname[:5] == 'linux':
  63.         return '%s-%s' % (osname, machine)
  64.     os.name == 'nt' if osname[:5] == 'sunos' else not hasattr(os, 'uname')
  65.     if osname[:3] == 'aix':
  66.         return '%s-%s.%s' % (osname, version, release)
  67.     if osname[:6] == 'cygwin':
  68.         osname = 'cygwin'
  69.         rel_re = re.compile('[\\d.]+')
  70.         m = rel_re.match(release)
  71.         if m:
  72.             release = m.group()
  73.         
  74.     elif osname[:6] == 'darwin':
  75.         get_config_vars = get_config_vars
  76.         import distutils.sysconfig
  77.         cfgvars = get_config_vars()
  78.         macver = os.environ.get('MACOSX_DEPLOYMENT_TARGET')
  79.         if not macver:
  80.             macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
  81.         
  82.         macrelease = macver
  83.         
  84.         try:
  85.             f = open('/System/Library/CoreServices/SystemVersion.plist')
  86.         except IOError:
  87.             pass
  88.  
  89.         m = re.search('<key>ProductUserVisibleVersion</key>\\s*' + '<string>(.*?)</string>', f.read())
  90.         f.close()
  91.         if m is not None:
  92.             macrelease = '.'.join(m.group(1).split('.')[:2])
  93.         
  94.         if not macver:
  95.             macver = macrelease
  96.         
  97.         if macver:
  98.             get_config_vars = get_config_vars
  99.             import distutils.sysconfig
  100.             release = macver
  101.             osname = 'macosx'
  102.             if macrelease + '.' >= '10.4.' and '-arch' in get_config_vars().get('CFLAGS', '').strip():
  103.                 machine = 'fat'
  104.                 cflags = get_config_vars().get('CFLAGS')
  105.                 archs = re.findall('-arch\\s+(\\S+)', cflags)
  106.                 archs.sort()
  107.                 archs = tuple(archs)
  108.                 if len(archs) == 1:
  109.                     machine = archs[0]
  110.                 elif archs == ('i386', 'ppc'):
  111.                     machine = 'fat'
  112.                 elif archs == ('i386', 'x86_64'):
  113.                     machine = 'intel'
  114.                 elif archs == ('i386', 'ppc', 'x86_64'):
  115.                     machine = 'fat3'
  116.                 elif archs == ('ppc64', 'x86_64'):
  117.                     machine = 'fat64'
  118.                 elif archs == ('i386', 'ppc', 'ppc64', 'x86_64'):
  119.                     machine = 'universal'
  120.                 else:
  121.                     raise ValueError("Don't know machine value for archs=%r" % (archs,))
  122.             len(archs) == 1
  123.             if machine in ('PowerPC', 'Power_Macintosh'):
  124.                 machine = 'ppc'
  125.             
  126.         
  127.     
  128.     return '%s-%s-%s' % (osname, release, machine)
  129.  
  130.  
  131. def convert_path(pathname):
  132.     """Return 'pathname' as a name that will work on the native filesystem,
  133.     i.e. split it on '/' and put it back together again using the current
  134.     directory separator.  Needed because filenames in the setup script are
  135.     always supplied in Unix style, and have to be converted to the local
  136.     convention before we can actually use them in the filesystem.  Raises
  137.     ValueError on non-Unix-ish systems if 'pathname' either starts or
  138.     ends with a slash.
  139.     """
  140.     if os.sep == '/':
  141.         return pathname
  142.     if not pathname:
  143.         return pathname
  144.     if pathname[0] == '/':
  145.         raise ValueError, "path '%s' cannot be absolute" % pathname
  146.     pathname[0] == '/'
  147.     if pathname[-1] == '/':
  148.         raise ValueError, "path '%s' cannot end with '/'" % pathname
  149.     pathname[-1] == '/'
  150.     paths = string.split(pathname, '/')
  151.     while '.' in paths:
  152.         paths.remove('.')
  153.         continue
  154.         pathname
  155.     if not paths:
  156.         return os.curdir
  157.     return apply(os.path.join, paths)
  158.  
  159.  
  160. def change_root(new_root, pathname):
  161.     '''Return \'pathname\' with \'new_root\' prepended.  If \'pathname\' is
  162.     relative, this is equivalent to "os.path.join(new_root,pathname)".
  163.     Otherwise, it requires making \'pathname\' relative and then joining the
  164.     two, which is tricky on DOS/Windows and Mac OS.
  165.     '''
  166.     if os.name == 'posix':
  167.         if not os.path.isabs(pathname):
  168.             return os.path.join(new_root, pathname)
  169.         return os.path.join(new_root, pathname[1:])
  170.     os.name == 'posix'
  171.     if os.name == 'nt':
  172.         (drive, path) = os.path.splitdrive(pathname)
  173.         if path[0] == '\\':
  174.             path = path[1:]
  175.         
  176.         return os.path.join(new_root, path)
  177.     if os.name == 'os2':
  178.         (drive, path) = os.path.splitdrive(pathname)
  179.         if path[0] == os.sep:
  180.             path = path[1:]
  181.         
  182.         return os.path.join(new_root, path)
  183.     if os.name == 'mac':
  184.         if not os.path.isabs(pathname):
  185.             return os.path.join(new_root, pathname)
  186.         elements = string.split(pathname, ':', 1)
  187.         pathname = ':' + elements[1]
  188.         return os.path.join(new_root, pathname)
  189.     os.name == 'mac'
  190.     raise DistutilsPlatformError, "nothing known about platform '%s'" % os.name
  191.  
  192. _environ_checked = 0
  193.  
  194. def check_environ():
  195.     """Ensure that 'os.environ' has all the environment variables we
  196.     guarantee that users can use in config files, command-line options,
  197.     etc.  Currently this includes:
  198.       HOME - user's home directory (Unix only)
  199.       PLAT - description of the current platform, including hardware
  200.              and OS (see 'get_platform()')
  201.     """
  202.     global _environ_checked
  203.     if _environ_checked:
  204.         return None
  205.     if os.name == 'posix' and 'HOME' not in os.environ:
  206.         import pwd as pwd
  207.         os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
  208.     
  209.     if 'PLAT' not in os.environ:
  210.         os.environ['PLAT'] = get_platform()
  211.     
  212.     _environ_checked = 1
  213.  
  214.  
  215. def subst_vars(s, local_vars):
  216.     """Perform shell/Perl-style variable substitution on 'string'.  Every
  217.     occurrence of '$' followed by a name is considered a variable, and
  218.     variable is substituted by the value found in the 'local_vars'
  219.     dictionary, or in 'os.environ' if it's not in 'local_vars'.
  220.     'os.environ' is first checked/augmented to guarantee that it contains
  221.     certain values: see 'check_environ()'.  Raise ValueError for any
  222.     variables not found in either 'local_vars' or 'os.environ'.
  223.     """
  224.     check_environ()
  225.     
  226.     def _subst(match, local_vars = local_vars):
  227.         var_name = match.group(1)
  228.         if var_name in local_vars:
  229.             return str(local_vars[var_name])
  230.         return os.environ[var_name]
  231.  
  232.     
  233.     try:
  234.         return re.sub('\\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
  235.     except KeyError:
  236.         var = None
  237.         raise ValueError, "invalid variable '$%s'" % var
  238.  
  239.  
  240.  
  241. def grok_environment_error(exc, prefix = 'error: '):
  242.     """Generate a useful error message from an EnvironmentError (IOError or
  243.     OSError) exception object.  Handles Python 1.5.1 and 1.5.2 styles, and
  244.     does what it can to deal with exception objects that don't have a
  245.     filename (which happens when the error is due to a two-file operation,
  246.     such as 'rename()' or 'link()'.  Returns the error message as a string
  247.     prefixed with 'prefix'.
  248.     """
  249.     if hasattr(exc, 'filename') and hasattr(exc, 'strerror'):
  250.         if exc.filename:
  251.             error = prefix + '%s: %s' % (exc.filename, exc.strerror)
  252.         else:
  253.             error = prefix + '%s' % exc.strerror
  254.     else:
  255.         error = prefix + str(exc[-1])
  256.     return error
  257.  
  258. _wordchars_re = None
  259. _squote_re = None
  260. _dquote_re = None
  261.  
  262. def _init_regex():
  263.     global _wordchars_re, _squote_re, _dquote_re
  264.     _wordchars_re = re.compile('[^\\\\\\\'\\"%s ]*' % string.whitespace)
  265.     _squote_re = re.compile("'(?:[^'\\\\]|\\\\.)*'")
  266.     _dquote_re = re.compile('"(?:[^"\\\\]|\\\\.)*"')
  267.  
  268.  
  269. def split_quoted(s):
  270.     '''Split a string up according to Unix shell-like rules for quotes and
  271.     backslashes.  In short: words are delimited by spaces, as long as those
  272.     spaces are not escaped by a backslash, or inside a quoted string.
  273.     Single and double quotes are equivalent, and the quote characters can
  274.     be backslash-escaped.  The backslash is stripped from any two-character
  275.     escape sequence, leaving only the escaped character.  The quote
  276.     characters are stripped from any quoted string.  Returns a list of
  277.     words.
  278.     '''
  279.     if _wordchars_re is None:
  280.         _init_regex()
  281.     
  282.     s = string.strip(s)
  283.     words = []
  284.     pos = 0
  285.     while s:
  286.         m = _wordchars_re.match(s, pos)
  287.         end = m.end()
  288.         if end == len(s):
  289.             words.append(s[:end])
  290.             break
  291.         
  292.         if s[end] in string.whitespace:
  293.             words.append(s[:end])
  294.             s = string.lstrip(s[end:])
  295.             pos = 0
  296.         elif s[end] == '\\':
  297.             s = s[:end] + s[end + 1:]
  298.             pos = end + 1
  299.         elif s[end] == "'":
  300.             m = _squote_re.match(s, end)
  301.         elif s[end] == '"':
  302.             m = _dquote_re.match(s, end)
  303.         else:
  304.             raise RuntimeError, "this can't happen (bad char '%c')" % s[end]
  305.         if s[end] in string.whitespace is None:
  306.             raise ValueError, 'bad string (mismatched %s quotes?)' % s[end]
  307.         s[end] in string.whitespace is None
  308.         (beg, end) = m.span()
  309.         s = s[:beg] + s[beg + 1:end - 1] + s[end:]
  310.         pos = m.end() - 2
  311.         if pos >= len(s):
  312.             words.append(s)
  313.             break
  314.             continue
  315.     return words
  316.  
  317.  
  318. def execute(func, args, msg = None, verbose = 0, dry_run = 0):
  319.     '''Perform some action that affects the outside world (eg.  by
  320.     writing to the filesystem).  Such actions are special because they
  321.     are disabled by the \'dry_run\' flag.  This method takes care of all
  322.     that bureaucracy for you; all you have to do is supply the
  323.     function to call and an argument tuple for it (to embody the
  324.     "external action" being performed), and an optional message to
  325.     print.
  326.     '''
  327.     if msg is None:
  328.         msg = '%s%r' % (func.__name__, args)
  329.         if msg[-2:] == ',)':
  330.             msg = msg[0:-2] + ')'
  331.         
  332.     
  333.     log.info(msg)
  334.     if not dry_run:
  335.         apply(func, args)
  336.     
  337.  
  338.  
  339. def strtobool(val):
  340.     """Convert a string representation of truth to true (1) or false (0).
  341.  
  342.     True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  343.     are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
  344.     'val' is anything else.
  345.     """
  346.     val = string.lower(val)
  347.     if val in ('y', 'yes', 't', 'true', 'on', '1'):
  348.         return 1
  349.     if val in ('n', 'no', 'f', 'false', 'off', '0'):
  350.         return 0
  351.     raise ValueError, 'invalid truth value %r' % (val,)
  352.  
  353.  
  354. def byte_compile(py_files, optimize = 0, force = 0, prefix = None, base_dir = None, verbose = 1, dry_run = 0, direct = None):
  355.     '''Byte-compile a collection of Python source files to either .pyc
  356.     or .pyo files in the same directory.  \'py_files\' is a list of files
  357.     to compile; any files that don\'t end in ".py" are silently skipped.
  358.     \'optimize\' must be one of the following:
  359.       0 - don\'t optimize (generate .pyc)
  360.       1 - normal optimization (like "python -O")
  361.       2 - extra optimization (like "python -OO")
  362.     If \'force\' is true, all files are recompiled regardless of
  363.     timestamps.
  364.  
  365.     The source filename encoded in each bytecode file defaults to the
  366.     filenames listed in \'py_files\'; you can modify these with \'prefix\' and
  367.     \'basedir\'.  \'prefix\' is a string that will be stripped off of each
  368.     source filename, and \'base_dir\' is a directory name that will be
  369.     prepended (after \'prefix\' is stripped).  You can supply either or both
  370.     (or neither) of \'prefix\' and \'base_dir\', as you wish.
  371.  
  372.     If \'dry_run\' is true, doesn\'t actually do anything that would
  373.     affect the filesystem.
  374.  
  375.     Byte-compilation is either done directly in this interpreter process
  376.     with the standard py_compile module, or indirectly by writing a
  377.     temporary script and executing it.  Normally, you should let
  378.     \'byte_compile()\' figure out to use direct compilation or not (see
  379.     the source for details).  The \'direct\' flag is used by the script
  380.     generated in indirect mode; unless you know what you\'re doing, leave
  381.     it set to None.
  382.     '''
  383.     if direct is None:
  384.         if __debug__:
  385.             pass
  386.         direct = optimize == 0
  387.     
  388.     if not direct:
  389.         
  390.         try:
  391.             mkstemp = mkstemp
  392.             import tempfile
  393.             (script_fd, script_name) = mkstemp('.py')
  394.         except ImportError:
  395.             mktemp = mktemp
  396.             import tempfile
  397.             script_fd = None
  398.             script_name = mktemp('.py')
  399.  
  400.         log.info("writing byte-compilation script '%s'", script_name)
  401.         if not dry_run:
  402.             if script_fd is not None:
  403.                 script = os.fdopen(script_fd, 'w')
  404.             else:
  405.                 script = open(script_name, 'w')
  406.             script.write('from distutils.util import byte_compile\nfiles = [\n')
  407.             script.write(string.join(map(repr, py_files), ',\n') + ']\n')
  408.             script.write('\nbyte_compile(files, optimize=%r, force=%r,\n             prefix=%r, base_dir=%r,\n             verbose=%r, dry_run=0,\n             direct=1)\n' % (optimize, force, prefix, base_dir, verbose))
  409.             script.close()
  410.         
  411.         cmd = [
  412.             sys.executable,
  413.             script_name]
  414.         if optimize == 1:
  415.             cmd.insert(1, '-O')
  416.         elif optimize == 2:
  417.             cmd.insert(1, '-OO')
  418.         
  419.         spawn(cmd, dry_run = dry_run)
  420.         execute(os.remove, (script_name,), 'removing %s' % script_name, dry_run = dry_run)
  421.     else:
  422.         compile = compile
  423.         import py_compile
  424.         for file in py_files:
  425.             if file[-3:] != '.py':
  426.                 continue
  427.             
  428.             if not __debug__ or 'c':
  429.                 pass
  430.             cfile = file + 'o'
  431.             dfile = file
  432.             if prefix:
  433.                 if file[:len(prefix)] != prefix:
  434.                     raise ValueError, "invalid prefix: filename %r doesn't start with %r" % (file, prefix)
  435.                 file[:len(prefix)] != prefix
  436.                 dfile = dfile[len(prefix):]
  437.             
  438.             if base_dir:
  439.                 dfile = os.path.join(base_dir, dfile)
  440.             
  441.             cfile_base = os.path.basename(cfile)
  442.             if direct:
  443.                 if force or newer(file, cfile):
  444.                     log.info('byte-compiling %s to %s', file, cfile_base)
  445.                     if not dry_run:
  446.                         compile(file, cfile, dfile)
  447.                     
  448.                 else:
  449.                     log.debug('skipping byte-compilation of %s to %s', file, cfile_base)
  450.             newer(file, cfile)
  451.         
  452.  
  453.  
  454. def rfc822_escape(header):
  455.     '''Return a version of the string escaped for inclusion in an
  456.     RFC-822 header, by ensuring there are 8 spaces space after each newline.
  457.     '''
  458.     lines = string.split(header, '\n')
  459.     lines = map(string.strip, lines)
  460.     header = string.join(lines, '\n' + '        ')
  461.     return header
  462.  
  463.